package com.fouram.mybatis.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.fouram.mybatis.plugins.SqlInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Collections;

@Configuration
@EnableTransactionManagement
@MapperScan({ "com.fouram.**.mapper" })
public class MybatisPlusConfig {

	/**
	 * 分页插件 3.5.X
	 * @author fouram
	 */
	@Bean
	public PaginationInnerInterceptor paginationInnerInterceptor() {
		PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor();
		paginationInterceptor.setDbType(DbType.MYSQL);
		// 开启 count 的 join 优化,只针对部分 left join
		paginationInterceptor.setOptimizeJoin(true);
		return paginationInterceptor;
	}

	@Bean
	public ConfigurationCustomizer mybatisConfigurationCustomizer() {
		return configuration -> {
			configuration.addInterceptor(new SqlInterceptor());
		};
	}

	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor(){
		MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
		mybatisPlusInterceptor.setInterceptors(Collections.singletonList(paginationInnerInterceptor()));
		return mybatisPlusInterceptor;
	}
}
